<template>
<div class="goodsClassify tree-page">
  <search-block>
    <template slot="button">
      <el-button @click="doFilter">查询</el-button>
      <el-button type="primary" @click="addClassify()">添加类别</el-button>
    </template>
    <el-form inline :model="search" label-width="100px">
      <el-form-item label="类别名称:">
        <el-input v-model="search.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="类别种类:">
        <el-select v-model="search.tag" clearable>
          <el-option :value="0" label="普通商品类别"></el-option>
          <el-option :value="1" label="物品商品类别"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </search-block>
  <div class="classify-tree-block tree-block tree-page-block">
    <el-tree
      :key="treeKey"
      ref="tree"
      :data="classifyData"
      accordion
      node-key="id"
      :filter-node-method="filterNode"
      :props="{ label: 'name', children: 'children' }"
      lazy
      :load="loadChild">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span class="tree-node-label">{{ node.label }}</span>
        <span class="tree-node-btn">
          <el-link
            v-if="node.level < 2"
            :underline="false"
            type="primary"
            @click="() => addClassify(node)">
            添加类别项
          </el-link>
          <el-link
            :underline="false"
            type="primary"
            @click="() => editClassify(node)">
            编辑
          </el-link>
          <el-popconfirm
            title="是否确认删除该类别项？"
            @confirm="delClassify(data)">
            <el-link
              disabled
              slot="reference"
              :underline="false"
              type="danger">
              删除
            </el-link>
          </el-popconfirm>
        </span>
      </span>
    </el-tree>
  </div>
  <y-form
    ref="yForm"
    :key="refreshKey"
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    title="添加类别"
    width="50%"
    destroy-on-close
    :formAttrs="forms.formAttrs"
    :columns="formColumns"
    @close="refreshKey+=2"
    @ensure="ensureModel">
    <template slot="level">
      <el-input v-model="forms.formModel.level" disabled style="width: 50px;margin-right: 10px"></el-input>级
    </template>
    <template slot="icon">
      <y-upload-img
        business-sys-module-code="GOODS_CLASSIFY"
        :limit="1"
        :url="forms.formModel.icon ? [{
            url: forms.formModel.icon,
            id: forms.formModel.attachmentId
          }] : []"
        value-type="ObjectArray"
        @update="updateModel"
        :cropper-options="{
          centerBox: false
        }"
        re-upload>
      </y-upload-img>
    </template>
  </y-form>
</div>
</template>

<script>
export default {
  name: "goodsClassify",
  computed:{
    formColumns(){
      return [
        {
          label: "上一级类别",
          prop: "parentName",
          comp:{
            compType: 'input',
            attrs:{
              disabled: true
            }
          }
        },
        {
          label: "类别名称",
          prop: "name",
          comp:{
            compType: 'input',
            attrs:{
              clearable: true,
              maxlength: 20,
              showWordLimit: true
            }
          }
        },
        {
          label: "当前级别",
          prop: "level",
          template: true
        },
        {
          label: "类别种类",
          prop: "tag",
          comp:{
            compType: 'select',
            options: [{
              label: '普通商品类别',
              value: 0
            },{
              label: '商品类别',
              value: 1
            }],
            attrs:{
              disabled: !!this.forms.formModel.id || this.forms.formModel.level === 2
            }
          }
        },
        {
          label: "图标",
          prop: "icon",
          template: true
        },
        {
          label: "排序",
          prop: "sort",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true
            }
          }
        },
        {
          label: "是否显示",
          prop: "showStatus",
          comp:{
            compType: 'switch',
            attrs:{
              activeValue: 1,
              inactiveValue: 0
            }
          }
        }
      ]
    }
  },
  data(){
    return{
      search:{
        name: '',
        tag: '',
      },
      classifyData: [],
      refreshKey: 0,
      treeKey: 1,
      filterTag: false,
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加类别',
          'EDIT': '编辑类别'
        },
        currentForm: null,
        formModel: {
          id: '',
          name: '',
          parentId: '',
          parentName: '',
          icon: '',
          showStatus: 1,
          level: 1,
          sort: ''
        },
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            name: [{required: true, message: "请输入商品类别", trigger: "blur"}],
            /*icon: [{required: true, message: "请选择商品图片", trigger: "blur"}]*/
          }
        }
      }
    }
  },
  methods:{
    refresh(){
      this.treeKey+=2;
      this.filterTag = true;
    },
    showYForm(){
      this.forms.showForm = true;
    },
    updateModel({type, file}){
      switch(type) {
        case 'delete': {
          this.forms.formModel.attachmentId = '';
          this.forms.formModel.icon = '';
          break;
        }
        case 'edit': case 'add':{
          this.forms.formModel.attachmentId = file.id;
          this.forms.formModel.icon = file.name;
          this.$refs['yForm'].$refs['form'].validateField('icon');
          break;
        }
      }
    },
    doFilter(){
      this.$refs.tree.filter([this.search.name, this.search.tag]);
    },
    filterNode([value, tag], data){
      const hasTag = !!tag || tag === 0;
      if (!value && !hasTag) return true;
      if(!hasTag){
        return data.name.indexOf(value) >= 0
      }
      if(!value){
        return data.tag === tag;
      }
      return data.name.indexOf(value) >= 0 && data.tag === tag;
    },
    loadChild(node,resolve){
      this.$yAxios({
        url: this.$api.goods.getChildClassify,
        data:{
          parentId: node.data.id || ''
        }
      },info => {
        if(this.filterTag){
          this.filterTag = false;
          this.$nextTick(() => {
            this.doFilter();
          })
        }
        resolve(info)
      }, () => {
        resolve([])
      })
    },
    resetForm(data = this.forms.currentForm){
      this.forms.formModel = Object.assign({
        id: '',
        name: '',
        parentId: '',
        parentName: '',
        icon: '',
        showStatus: 1,
        tag: 0,
        level: 1,
        sort: ''
      }, data)
    },
    addClassify({level, data} = {level: 0, data: {id: '', name: '无'}}){
      if(level === 2){
        this.$alert('无法在2级目录下添加类别', {
          confirmButtonText: '确定'
        });
        return;
      }
      this.forms.formsType = 'ADD';
      this.forms.currentForm = data;
      this.resetForm({
        parentId: data.id,
        parentName: data.name,
        tag: data.tag || 0,
        level: level + 1
      });
      this.showYForm();
    },
    editClassify({level, data}){
      this.forms.formsType = 'EDIT';
      let pNode = this.$refs['tree'].getNode(data.parentId);
      if(pNode){
        data.parentName = pNode.data.name;
      }
      this.forms.currentForm = data;
      this.resetForm();
      this.showYForm();
    },
    delClassify(data){
      if(data.children && data.children.length){
        this.$alert('无法删除包含子类别的商品类别', {
          confirmButtonText: '确定'
        });
        return;
      }
      this.$yAxios({
        url: this.$api.goods.removeClassify,
        data:{
          id: data.id
        },
        loading: true
      }, info => {
        let pArray = this.classifyData, pId = data.parentId
        if(pId){
          let PNode = this.$refs['tree'].getNode(pId);
          pArray = PNode.data.children;
        }
        //let index = pArray.indexOf(data);
        this.$refs['tree'].remove(data);
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.$bus.$emit('refreshGoodsClassify');
      })
    },
    ensureModel(form){
      let newForm, url;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
        url = this.$api.goods.updateClassify;
      }else{
        newForm = Object.assign({}, form);
        url = this.$api.goods.addClassify
      }
      this.$yAxios({
        url,
        data: newForm,
        loading: true
      }, info => {
        if(info) newForm = info;
        switch(this.forms.formsType){
          case 'ADD':{
            if(this.forms.currentForm && this.forms.currentForm.id){//添加字典项
              if(!this.forms.currentForm.children){
                this.$set(this.forms.currentForm, 'children', []);
              }
              this.$refs['tree'].getNode(this.forms.currentForm).expanded = true;
              this.$refs['tree'].append(newForm, this.forms.currentForm);
            }else{//添加字典
              this.refresh();
            }
            break;
          }
          case 'EDIT':{
            Object.assign(this.forms.currentForm, newForm);
            break;
          }
        }
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.$bus.$emit('refreshGoodsClassify');
      })
    }
  }
}
</script>

<style scoped lang="less">
</style>